package com.sntk.organauthomanager.application.mapper;

import com.sntk.organauthomanager.application.dto.OrganizationDTO;
import com.sntk.organauthomanager.application.dto.OrganizationVO;
import com.sntk.organauthomanager.infrastructure.db.entity.OrganizationEntity;
import com.sntk.organauthomanager.infrastructure.db.entity.UserEntity;
import com.sntk.organauthomanager.infrastructure.db.repository.OrganizationDBRepository;
import com.sntk.organauthomanager.infrastructure.db.repository.UserDBRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @ClassName: OrganizationMapper
 * @author: wgchao
 * @createTime: 2020/7/20 6:45 PM
 * @Description: TODO
 */
@Component
public class OrganizationMapper {
    @Autowired
    private OrganizationDBRepository organizationDBRepository;
    @Autowired
    private UserDBRepository userDBRepository;

    public OrganizationDTO transformToDTO(OrganizationEntity entity){
        OrganizationDTO dto = new OrganizationDTO();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    public OrganizationVO transformToVO(OrganizationEntity entity){
        OrganizationVO vo = new OrganizationVO();
        BeanUtils.copyProperties(entity, vo);

        if(!StringUtils.isEmpty(entity.getSuperiorNumber())){
            OrganizationEntity superior = organizationDBRepository.findFirstByInstitutionNumberAndDelFalse(entity.getSuperiorNumber());
            if(superior != null){
                vo.setSuperiorName(superior.getInstitutionName());
            }
        }

        if(!StringUtils.isEmpty(entity.getCreator())){
            UserEntity creator = userDBRepository.findFirstByUnameAndDelFalse(entity.getCreator());
            if(creator != null){
                vo.setCreatorName(creator.getUserName());
            }
        }
        if(!StringUtils.isEmpty(entity.getLastUpdator())){
            UserEntity updator = userDBRepository.findFirstByUnameAndDelFalse(entity.getLastUpdator());
            if(updator != null){
                vo.setLastUpdatorName(updator.getUserName());
            }
        }

        return vo;
    }
}
